<?php

namespace App\Admin\Forms;

use App\Http\Logic\OrderLogic;
use App\Models\SwtOrder;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class RefundOrderForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $id = $this->payload['id'] ?? null;

        $order_info = SwtOrder::firstWhere('id',$id) -> toArray();

        $out_order_no = $order_info['order_sn'];

        $amount = ($order_info['pay_amount'] - $order_info['refund_amount']) / 100;

        if($amount < $input['amount']) {
            return $this->response()->error('退款金额不足');
        }

        $amount = $input['amount'] * 100;

        switch($order_info['pay_type'])
        {
            case 0:
                $res = OrderLogic::refundOrder($out_order_no, $amount, '商家退款');
            break;
            case 1:
                $res = OrderLogic::refundOrderByJsApi($order_info['out_trade_no'], $amount, '商家退款');
            break;
            case 2:
                $res = OrderLogic::refundOrder($out_order_no, $amount, '商家退款');
            break;
        }

        if (!$res) {
            return $this->response()->error('退款失败');
        }

        return $this->response()->success('退款成功')->refresh();
    }

    public function form()
    {
        $this->currency('amount','退款金额')->symbol('￥') -> rules('required|min:0');
    }

    public function default()
    {
        $id = $this->payload['id'] ?? null;

        $order_info = SwtOrder::where('id',$id)->firstOrFail();

        $order_info = $order_info -> toArray();

        $amount = ($order_info['pay_amount'] - $order_info['refund_amount']) / 100;

        return [
            'amount' => $amount
        ];
    }
}
